<template>
  <div>
    <Form
      :select-show="true"
      oneitem="点位搜索"
      twoitem="区域搜索"
      :total-count="totalCount"
      :total-page="totalPage"
      :page-index="pageIndex"
      :search-list="nodeList"
      :option="option"
      @changeList="changeList"
      @newCreateFn="newCreateFn"
    >
      <template #tableForm>
        <el-table-column label="序号" width="80" type="index" :index="indexMethod" />
        <el-table-column prop="name" label="点位名称" />
        <el-table-column prop="region.name" label="所在区域" />
        <el-table-column prop="businessType.name" label="商圈类型" />
        <el-table-column prop="ownerName" label="合作商" />
        <el-table-column prop="addr" label="详细地址" />
        <el-table-column prop="address" label="操作" width="200">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleClick(scope.row)">查看详情</el-button>
            <el-button type="text" @click="edit(scope.row)">修改</el-button>
            <el-button type="text" style="color:red" @click="del(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </template>
    </Form>
    <el-dialog
      title="新增点位"
      :visible.sync=" regionVisible"
      width="630px"
      @closed="regionInfoClose"
      @open="regionInfoOpen"
    >
      <el-form ref="nodeForm" :model="nodeForm" label-width="140px" :rules="nodeRules">
        <el-form-item label="点位名称：" prop="name">
          <el-input v-model="nodeForm.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="所在区域：" prop="area">
          <el-select v-model="nodeForm.area" placeholder="请选择">
            <el-option v-for="item in option" :key="item.value" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="归属商圈：" prop="business">
          <el-select v-model="nodeForm.business" placeholder="请选择">
            <el-option v-for="item in businessList" :key="item.value" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="归属合作商：" prop="owner">
          <el-select v-model="nodeForm.owner" placeholder="请选择">
            <el-option v-for="item in ownerList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址：" prop="detailAddr">
          <el-cascader v-model="nodeForm.detailAddr" size="large" :options="options" />
          <!-- @change="handleChange" -->
        </el-form-item>
        <el-form-item prop="addr">
          <el-input v-model="nodeForm.addr" type="textarea" placeholder="请输入内容" maxlength="60" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button id="buttom2" @click="regionVisible=false">取 消</el-button>
        <el-button id="buttom1" type="primary" @click="addNode">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="区域详情" :visible.sync="nodeInfoVisible" width="630px">
      <el-table :data="nodeInfoList" style="width: 100%">
        <el-table-column label="序号" width="100" type="index" />
        <el-table-column prop="innerCode" label="机器编号" width="150" />
        <el-table-column prop="vmStatus" label="设备状态">
          <template slot-scope="scope">
            <span>{{ scope.row.vmStatus }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="lastSupplyTime" label="最后一次供货时间" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
import Form from '@/components/form/index.vue'
import { regionSearch, nodeSearch, businessType, partnerSearch, addNode, vmList, editNode, delNode } from '@/api'
export default {
  components: { Form },
  data() {
    return {
      pageIndex: 1,
      nodeList: [], // 列表
      totalPage: null,
      totalCount: null,
      option: [],
      regionVisible: false,
      // 新增点位
      nodeForm: {
        name: null, // 点位名称
        area: null, // 所在区域
        business: null, // 所属商圈
        addr: null, // 详细地址
        owner: null, // 归属合作商
        detailAddr: null
      },
      nodeRules: {
        name: [
          { required: true, message: '请输入' }
        ],
        area: [
          { required: true, message: '请输入' }
        ],
        business: [
          { required: true, message: '请输入' }
        ],
        addr: [
          { required: true, message: '请输入' }
        ],
        owner: [
          { required: true, message: '请输入' }
        ],
        detailAddr: [
          { required: true, message: '请输入' }
        ]
      },
      businessList: null, // 归属商圈
      ownerList: null, // 归属合作商
      nodeInfoVisible: false,
      nodeInfoList: null, // 点位详情
      options: regionData, // 地区选择
      editRow: null
    }
  },
  computed: {
    title() {
      return this.regionForm.id ? '修改区域' : '新增区域'
    }
  },
  created() {
    this.nodeSearch()
  },
  methods: {
    handleChange(value) {
      console.log(value)
    },
    // 列表
    async nodeSearch(pageIndex, name) {
      const { data } = await nodeSearch({
        pageIndex,
        name
      })
      data.currentPageRecords.forEach(item => {
        item.addr = item.addr.split('-').at(-1)
      })
      this.nodeList = data.currentPageRecords
      this.totalPage = data.totalPage
      this.totalCount = data.totalCount
      const res = await regionSearch({ pageIndex: 1, pageSize: 100000 })
      this.option = res.data.currentPageRecords
      this.option.forEach(item => {
        item.statusId = item.id
        item.statusName = item.name
      })
      console.log(this.option)
    },
    indexMethod(index) {
      return this.pageIndex === 1 ? index + 1 : Number(`${this.pageIndex - 1}${index}`) + 1
    },
    changeList(page) {
      this.pageIndex = page
      this.nodeSearch(this.pageIndex)
    },
    // 新建
    newCreateFn() {
      this.regionVisible = true
    },
    // 弹窗出现
    async regionInfoOpen() {
      const res = await businessType()
      const res1 = await partnerSearch({
        pageSize: 10000,
        pageIndex: 1
      })
      this.businessList = res.data
      this.ownerList = res1.data.currentPageRecords
    },
    // 添加接口
    addNode() {
      this.$refs.nodeForm.validate(async(valid) => {
        if (!valid) return
        // 地区字符串处理
        let str
        this.nodeForm.detailAddr.forEach(item => {
          str = CodeToText[item] + '-' + CodeToText[item] + '-' + CodeToText[item]
        })
        const params = {
          addr: str + '-' + this.nodeForm.addr,
          areaCode: this.nodeForm.detailAddr[2],
          businessId: this.nodeForm.business,
          createUserId: this.$store.state.user.userId,
          name: this.nodeForm.name,
          ownerId: this.nodeForm.owner,
          ownerName: this.nodeForm.owner,
          regionId: this.nodeForm.area
        }
        console.log(params)
        if (this.editRow) {
          this.option.forEach(item => {
            if (item.name === params.regionId) {
              params.regionId = item.id
            }
          })
          this.businessList.forEach(item => {
            if (item.name === params.businessId) {
              params.businessId = item.id
            }
          })
          console.log(params.businessId)
          this.ownerList.forEach(item => {
            if (item.name === params.businessId) {
              console.log(item)
              params.ownerId = item.id
            } else {
              params.ownerId = item.id
            }
          })
          console.log(params)
          await editNode(this.editRow.id, params)
        } else {
          const ownerName = this.ownerList.filter(item => {
            return item.id === this.nodeForm.owner
          })
          params.ownerName = ownerName.name
          const res = await addNode(params)
          if (res.data) {
            this.$message({ type: 'success', message: '添加成功' })
          }
        }
        this.regionVisible = false
        this.nodeSearch()
      })
    },
    // 查看详情
    async handleClick(row) {
      const res = await vmList(row.id)
      console.log(res.data)
      res.data.forEach(item => {
        if (item.vmStatus === 0) {
          item.vmStatus = '未投放'
        } else if (item.vmStatus === 1) {
          item.vmStatus = '运营'
        } else {
          item.vmStatus = '撤机'
        }
        item.lastSupplyTime = item.lastSupplyTime.replace('-', '.').replace('T', ' ')
      })
      this.nodeInfoList = res.data
      this.nodeInfoVisible = true
    },
    // 修改
    async edit(row) {
      console.log(row)
      this.regionVisible = true
      const { data: { currentPageRecords: res }} = await nodeSearch({ name: row.name })
      this.editRow = res[0]
      console.log(this.editId)
      const detailAddr = []
      const addrList = res[0].addr.split('-').slice(0, 3)
      detailAddr.push(TextToCode[addrList[0]].code)
      detailAddr.push(TextToCode[addrList[0]][addrList[1]].code)
      detailAddr.push(TextToCode[addrList[0]][addrList[1]][addrList[2]].code)
      this.nodeForm = {
        name: res[0].name, // 点位名称
        area: res[0].region.name, // 所在区域
        business: res[0].businessType.name, // 所属商圈
        addr: res[0].addr.split('-').at(-1), // 详细地址
        owner: res[0].ownerName, // 归属合作商
        detailAddr
      }
      console.log(this.nodeForm)
    },
    // 删除
    del(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delNode(row.id)
        this.nodeSearch(this.pageIndex)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 关闭
    regionInfoClose() {
      this.channelInfo = null
      this.$refs.nodeForm.resetFields()
    }
    // }
  }
}
</script>

<style lang="scss" scoped>
#buttom1 {
  align-items: center;
  width: 80px !important;
  height: 36px;
  padding: 0;
  background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
  color: #fff;
  border: none;
}

#buttom2 {
  align-items: center;
  width: 80px !important;
  height: 36px;
  padding: 0;
  background-color: #fbf4f0 !important;
  border: none;
  color: #655b56 !important;
}
</style>
